package Filesharing;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import login.UserModel;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;

import OpenFile.OpenFile;

public class FileAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		FileForm fileShareForm = (FileForm) form;
		FileManager filesharingManager = new FileManager();
		HttpSession session = request.getSession(true);
		Boolean isOpenFile = false;
						
		//utk dapetin usermodel dr session (update/delete file)
		UserModel user = (UserModel)session.getAttribute("userLogin");
		
		if("openFile".equalsIgnoreCase(fileShareForm.getTask())) {
			OpenFile op = new OpenFile();
			String directoryPath = "tesUploadFile/";
			String filePath = getServlet().getServletContext().getRealPath("/") + directoryPath;
			filePath += fileShareForm.getPathOpenFile();
			op.openFile(filePath);
			isOpenFile = true;
			//scheduleForm.setTask(null);
		}
		if ("listFile".equalsIgnoreCase(fileShareForm.getTask())) {
			fileShareForm.setListFile(setIsFileExistLst(filesharingManager.selectAllFile(fileShareForm)));
			request.setAttribute("listFile", fileShareForm.getListFile()); //checking file type
			return mapping.findForward("manageFile");
		}
		if ("insertFile".equalsIgnoreCase(fileShareForm.getTask())) {
			String title = "Upload File";
			fileShareForm.setTask("uploadFile");
			request.setAttribute("title",title);
			fileShareForm.getModelFile().setFileName(null);
			return mapping.findForward("insertFile");
		}
		if ("uploadFile".equalsIgnoreCase(fileShareForm.getTask())) {
			if (fileShareForm.getModelFile().getDescription() == null) {
				fileShareForm.getModelFile().setDescription(null);
			}
			
			// Process the FormFile
			FormFile myFile = fileShareForm.getTheFile();
			String contentType = myFile.getContentType();
			
			//Get the file name
			String fileName  = myFile.getFileName();
			
			//int fileSize = myFile.getFileSize();
			byte[] fileData  = myFile.getFileData();
			
			//Get the servers upload directory real path name
			String directoryPath = "tesUploadFile/";
			fileShareForm.getModelFile().setFilePath(directoryPath);
			fileShareForm.getModelFile().setUploaderId(user.getUserid());
			String filePath = getServlet().getServletContext().getRealPath("/") +directoryPath;
			
			if(myFile.getFileSize() <= 5000000) {
				/* Save file on the server */
				if(!fileName.equals("")){  
					//Create file
					File fileToCreate = new File(filePath, fileName);
					  
					//If file does not exists create file  
					if(!fileToCreate.exists()){
						FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
						fileOutStream.write(myFile.getFileData());
						fileOutStream.flush();
						fileOutStream.close();
						filesharingManager.addFile(fileShareForm.getModelFile());
					} else {
						Integer curFileId = filesharingManager.getCurFileId();
						String oldFileName = fileName.substring(0,fileName.lastIndexOf("."));
						String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
						String newFileName = oldFileName + " - " + curFileId + fileType;
					
					    // File (or directory) with new name
					    File file2 = new File(filePath, newFileName);
					    /*if(file2.exists()) throw new java.io.IOException("file exists");*/

					    // Rename file (or directory)
					    boolean success = fileToCreate.renameTo(file2);
					    if (!success) {
					        // File was not successfully renamed
					    	session.setAttribute("result", "File was not successfully renamed");
					    } else {
					    	FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
							fileOutStream.write(myFile.getFileData());
							fileOutStream.flush();
							fileOutStream.close();
							fileShareForm.getModelFile().setFileName(newFileName);
					    	filesharingManager.addFile(fileShareForm.getModelFile());
						}
					}
				}
				
				String fullFilePath = filePath+fileName;
				  
				//Set file name to the request object
				request.setAttribute("directoryPath",directoryPath);
				request.setAttribute("fileName",fileName);
				
				//utk notification crud
				session.setAttribute("result", "Upload File success");
				
				fileShareForm.setListFile(setIsFileExistLst(filesharingManager.selectAllFile(fileShareForm)));
				request.setAttribute("listFile", fileShareForm.getListFile());
				fileShareForm.setTask("listFile");
				//fileShareForm.getModelFile().setFileName(null);
				return mapping.findForward("manageFile");
			}
		}
		if ("updateFile".equalsIgnoreCase(fileShareForm.getTask())) {
			if (fileShareForm.getModelFile().getUploaderId().equalsIgnoreCase(user.getUserid()) || user.getRole().equalsIgnoreCase("admin")) {
				String title = "Update File";
				
				//untuk ngeset model bwt update
				fileShareForm.setModelFile(filesharingManager.selectFile(fileShareForm.getModelFile().getFileId()));
				fileShareForm.setTask("editFile");
				request.setAttribute("title",title);
				//fileShareForm.getModelFile().setFileName(null);
				return mapping.findForward("insertFile");
			} else {
				
				fileShareForm.setListFile(setIsFileExistLst(filesharingManager.selectAllFile(fileShareForm)));
				request.setAttribute("listFile", fileShareForm.getListFile());
				return mapping.findForward("manageFile");
			}
						
		}
		if ("editFile".equalsIgnoreCase(fileShareForm.getTask())) {
			if (fileShareForm.getModelFile().getDescription() == null) {
				fileShareForm.getModelFile().setDescription(null);
			}
									  
			//Utk Query Update
			FileModel fmNewFile = fileShareForm.getModelFile();
			if(fmNewFile.getFileName()!=null && !fmNewFile.getFileName().equalsIgnoreCase("")) {
				
				// Process the FormFile
				FormFile myFile = fileShareForm.getTheFile();
				String contentType = myFile.getContentType();
				  
				//Get the file name
				String fileName  = myFile.getFileName();
				
				//int fileSize = myFile.getFileSize();
				byte[] fileData  = myFile.getFileData();
				  
				//Get the servers upload directory real path name
				String directoryPath = "tesUploadFile/";
				fileShareForm.getModelFile().setFilePath(directoryPath);
				fileShareForm.getModelFile().setUploaderId(user.getUserid());
				String filePath = getServlet().getServletContext().getRealPath("/") +directoryPath;
				  
				//ngambil id file yg lama (yg mau direplace) -> DB tujuan buat delete file yang lama
				fileShareForm.setModelFile(filesharingManager.selectFile(fileShareForm.getModelFile().getFileId()));
				
				/*mulai dr sini fileshareform.getmodelfile = data yang lama*/
				
				//delete file dari folder
				directoryPath = fileShareForm.getModelFile().getFilePath();
				filePath = getServlet().getServletContext().getRealPath("/") +directoryPath +fileShareForm.getModelFile().getFileName();
					
				File myFile2 = new File(filePath);
				if (!myFile2.isDirectory()) {
					myFile2.delete();
				}
				  				  
				//mulai proses update file ke folder
				fileName = fmNewFile.getFileName();
				filePath = fmNewFile.getFilePath();
				  
				filePath = getServlet().getServletContext().getRealPath("/") +filePath;
				
				if(myFile.getFileSize() <= 5000000) {
					//Save file on the server 
					if(!fileName.equals("")){  
						//Create file
						File fileToCreate = new File(filePath, fileName);
						
						//If file does not exists create file  
						if(!fileToCreate.exists()){
							FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
							fileOutStream.write(myFile.getFileData());
							fileOutStream.flush();
							fileOutStream.close();
							filesharingManager.updateFile(fmNewFile);
							System.out.println("Testing file not exist");
							  
						} else {
							String selectedFileId = fileShareForm.getModelFile().getFileId();
							String oldFileName = fileName.substring(0,fileName.lastIndexOf("."));
							String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
							String newFileName = oldFileName + " - " + selectedFileId + fileType;
						
						    // File (or directory) with new name
						    File file2 = new File(filePath, newFileName);
						    /*if(file2.exists()) throw new java.io.IOException("file exists");*/

						    // Rename file (or directory)
						    boolean success = fileToCreate.renameTo(file2);
						    if (!success) {
						        // File was not successfully renamed
						    	System.out.println("File was not successfully renamed");
						    	session.setAttribute("result", "File was not successfully renamed");
						    } else {
						    	FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
								fileOutStream.write(myFile.getFileData());
								fileOutStream.flush();
								fileOutStream.close();
								fmNewFile.setFileName(newFileName);
								filesharingManager.updateFile(fmNewFile);
							}
						}
					}
					
					String fullFilePath = filePath+fileName;
					  
					//Set file name to the request object
					request.setAttribute("directoryPath",directoryPath);
					request.setAttribute("fileName",fileName);
								
			    }
				  
					//utk notification crud
					session.setAttribute("result", "Update File success");
				  	
					fileShareForm.setListFile(setIsFileExistLst(filesharingManager.selectAllFile(fileShareForm)));
					request.setAttribute("listFile", fileShareForm.getListFile());
				  	//fileShareForm.getModelFile().setFileName(null);
				  	return mapping.findForward("manageFile");
			}
		}
		if ("deleteFile".equalsIgnoreCase(fileShareForm.getTask())) {
			if (fileShareForm.getModelFile().getUploaderId().equalsIgnoreCase(user.getUserid()) || user.getRole().equalsIgnoreCase("admin")) {
				
				if (!fileShareForm.getModelFile().getFileId().equalsIgnoreCase("0")) {
					fileShareForm.setModelFile(filesharingManager.selectFile(fileShareForm.getModelFile().getFileId()));
					
					//utk ngehandle refresh stlh delete file
					if (fileShareForm.getModelFile() == null) {
						fileShareForm.setTask("fileSharing");
						return mapping.findForward("manageFile");
					}
					if(fileShareForm.getModelFile().getFilePath() == null){
						fileShareForm.setTask("fileSharing");
						return mapping.findForward("manageFile");
					}
					
					String directoryPath = fileShareForm.getModelFile().getFilePath();
					String filePath = getServlet().getServletContext().getRealPath("/") +directoryPath +fileShareForm.getModelFile().getFileName();
					
					File myFile = new File(filePath);
					if (!myFile.isDirectory()) {
						myFile.delete();
					}
					
					filesharingManager.deleteFile(fileShareForm.getModelFile().getFileId());
				}
				
				//utk notification crud
				session.setAttribute("result", "Delete File success");
				
				fileShareForm.setListFile(setIsFileExistLst(filesharingManager.selectAllFile(fileShareForm)));
				request.setAttribute("listFile", fileShareForm.getListFile());
				fileShareForm.getModelFile().setFileName(null);
				//fileShareForm.setTask("fileSharing");
				return mapping.findForward("manageFile");
			} else {
				
				fileShareForm.setListFile(setIsFileExistLst(filesharingManager.selectAllFile(fileShareForm)));
				request.setAttribute("listFile", fileShareForm.getListFile());
				return mapping.findForward("manageFile");
			}
		}	

		fileShareForm.setListFile(setIsFileExistLst(filesharingManager.selectAllFile(fileShareForm)));
		request.setAttribute("listFile", fileShareForm.getListFile());
		return mapping.findForward("manageFile");
	}
	
	
	private List setIsFileExistLst(List tmpLst){
		List result = new ArrayList();
		if(tmpLst != null) {
			int size = tmpLst.size();
			for(int i=0; i<size; i++) {
				FileModel tmpFileMod = (FileModel) tmpLst.get(i);
				String filePath = getServlet().getServletContext().getRealPath("/") +tmpFileMod.getFilePath();
				File fileToCreate = new File(filePath, tmpFileMod.getFileName());
				if(!fileToCreate.exists()){ // File is not exist
					tmpFileMod.setIsFileExist(false);
				} else {
					tmpFileMod.setIsFileExist(true);
				}
				result.add(tmpFileMod);
			}
		}
		
		return result;
	}
	
}
